import os

from django import http
import django.template as template
from django.conf import settings
import django.template.loader as loader
import django.core.urlresolvers as urlresolvers

import google.appengine.ext.db as db
from google.appengine.ext.db import Key

from models import Game
from games.gameList import gameList
from embedView import EmbedView

def _loadAllGames(crateInstance = False):
    gameDict = {}
    embedViewDict = {}
    embedViewObjectDict = {}
     
    for gameName in gameList.keys() :
        gameModule = __import__('games.' + gameList[gameName] + '.' + gameList[gameName] + 'Models', 
                                globals(), locals(), [], -1)        
        gameModule = getattr(gameModule, gameList[gameName])
        gameModule = getattr(gameModule, gameList[gameName] + 'Models')
        
        embedViewModule = __import__('games.' + gameList[gameName] + '.' + gameList[gameName] + 'EmbedView', 
                                     globals(), locals(), [], -1)
        embedViewModule = getattr(embedViewModule, gameList[gameName])
        embedViewModule = getattr(embedViewModule, gameList[gameName] + 'EmbedView')
        
        gameClass = getattr(gameModule, gameList[gameName] + 'Game')
        embedViewClass = getattr(embedViewModule, gameList[gameName] + 'EmbedView')
        
        gameDict[gameClass] = gameClass
        embedViewDict[gameClass] = embedViewClass
        if crateInstance :
            embedViewObjectDict[gameClass] = embedViewClass()
        else :
            embedViewObjectDict[gameClass] = None
        
        #raise Exception, str(gameClass)
    
    return gameDict, embedViewDict, embedViewObjectDict

def _loadGame(gameName):
    gameModule = __import__('games.' + gameList[gameName] + '.' + gameList[gameName] + 'Models', 
                            globals(), locals(), [], -1)        
    gameModule = getattr(gameModule, gameList[gameName])
    gameModule = getattr(gameModule, gameList[gameName] + 'Models')
    
    embedViewModule = __import__('games.' + gameList[gameName] + '.' + gameList[gameName] + 'EmbedView', 
                                 globals(), locals(), [], -1)
    embedViewModule = getattr(embedViewModule, gameList[gameName])
    embedViewModule = getattr(embedViewModule, gameList[gameName] + 'EmbedView')
    
    gameClass = getattr(gameModule, gameList[gameName] + 'Game')
    embedViewClass = getattr(embedViewModule, gameList[gameName] + 'EmbedView')
    
    return gameClass, embedViewClass

def index(request):
    
    gameDict, embedViewDict, embedViewObjectDict = _loadAllGames()
    
    r = http.HttpResponse('')
    
    games = Game.all().fetch(100)
    
    listViewArr = []
    for i in games :
        if embedViewObjectDict[type(i)] == None: 
            embedViewObjectDict[type(i)] = embedViewDict[type(i)]()
        
        embedViewObject = embedViewObjectDict[type(i)]
        
        dict = {}
        dict['displayName'] = embedViewObject.gameText('displayName')
        dict['link'] = urlresolvers.reverse('views.play', 
                                           kwargs={
                                                'gameName': i.gameType,
                                                'gameKeyStr': str(i.key()) 
                                                }
                                           )
        dict['key'] = str(i.key())
        dict['content'] = embedViewObject.gameListView(i)['content']
        listViewArr.append(dict)
    
    template_values = {
        'listViewArr': listViewArr,
    }
    
    r.write(loader.render_to_string('index.html', template_values))
    
    return r

def newGameEntry(request):
    gameDict, embedViewDict, embedViewObjectDict = _loadAllGames(True)
    
    gameArr = []
    
    games = Game.all().fetch(100)
    
    for k in embedViewObjectDict :
        embedViewObject = embedViewObjectDict[k]
        dict = {}
        dict['displayName'] = embedViewObject.gameText('displayName')
        dict['gameName'] = embedViewObject.gameName
        gameArr.append(dict)
    
    template_values = {
        'gameArr': gameArr,
    }
    
    r = http.HttpResponse('')
    r.write(loader.render_to_string('newGameEntry.html', template_values))
    
    return r

def newGame(request, gameName):
    r = http.HttpResponse('')
    
    gameClass, embedViewClass = _loadGame(gameName)
    embedViewObject = embedViewClass()
    
    embedViewNewGameRet = embedViewObject.newGame(request)
    
    if embedViewNewGameRet['action'] == EmbedView.ACTION_REDIRECT :
        return http.HttpResponseRedirect(embedViewNewGameRet['target'])
    
    template_values = {
        'displayName' : embedViewObject.gameText('displayName'),
        'gameName' : gameName, 
        'embedViewContent' : embedViewNewGameRet['content'],
    }
    
    r.write(loader.render_to_string('newGame.html', template_values))
    
    return r

def play(request, gameName, gameKeyStr):
    gameKey = Key(gameKeyStr)
    
    gameClass, embedViewClass = _loadGame(gameName)
    embedViewObject = embedViewClass()
    
    embedViewNewGameRet = embedViewObject.play(request, gameKey)
    
    if embedViewNewGameRet['action'] == None : 
        layoutType, layoutParameter = embedViewNewGameRet['layout']
        
        if layoutType == EmbedView.LAYOUT_PLAY_HORIZONTAL :
            r = http.HttpResponse('')
            
            roundBlockCount = layoutParameter            
            roundBlockContent = []
            for i in range(0, roundBlockCount) :
                roundBlockContent.append(embedViewNewGameRet['content']['round_%s' % i])
            #raise Exception, str(roundBlockContent)
            template_values = {
                'displayName' : embedViewObject.gameText('displayName'),
                'game' : embedViewNewGameRet['content']['game'], 
                'controlBlockContent' : embedViewNewGameRet['content']['control'], 
                'roundBlockContent' : roundBlockContent,
            }
            
            r.write(loader.render_to_string('playLayoutHorizontal.html', template_values))
            
            return r
    else :
        pass
    

def newgame1(request):
    
    from games.OfficialMahjong.OfficialMahjongModels import OfficialMahjongGame
    from games.OfficialMahjong.OfficialMahjongModels import OfficialMahjongSession
    from games.OfficialMahjong.OfficialMahjongModels import OfficialMahjongHand
    
    game = OfficialMahjongGame(name = 'test1', 
                               gameType = 'official_mahjong',
                               players = [u'p1', u'p2', u'p3', u'p4'], 
                               totalSessions = 4,
                               roundsForNow = 1)
    game.put()
    
    session = OfficialMahjongSession(game = game,
                                     players = [u'p1', u'p2', u'p3', u'p4'],
                                     roundNumber = 0,
                                     roundsForNow = 4,
                                     sumFans = [7, 9, 8, -14],
                                     parent = game)
    session.put()
    
    hand = OfficialMahjongHand(session = session, 
                               roundNumber = 0,
                               players = [u'p1', u'p2', u'p3', u'p4'],
                               fans = [8, -8 , 0, 0],
                               roundWind = 'east',
                               seatWind = 'east',
                               parent = session)
    hand.put()
    hand = OfficialMahjongHand(session = session, 
                               roundNumber = 1,
                               players = [u'p3', u'p4', u'p1', u'p2'],
                               fans = [8, -8 , 0, 0],
                               roundWind = 'east',
                               seatWind = 'south',
                               parent = session)
    hand.put()
    hand = OfficialMahjongHand(session = session, 
                               roundNumber = 2,
                               players = [u'p1', u'p3', u'p2', u'p4'],
                               fans = [-1, 2, -4, 3],
                               roundWind = 'east',
                               seatWind = 'west',
                               parent = session)
    hand.put()
    hand = OfficialMahjongHand(session = session, 
                               roundNumber = 3,
                               players = [u'p1', u'p2', u'p3', u'p4'],
                               fans = [0, 0 , 0, 0],
                               roundWind = 'east',
                               seatWind = 'north',
                               parent = session)
    hand.put()
#    hand = OfficialMahjongHand(session = session, 
#                               roundNumber = 4,
#                               players = [u'p3', u'p1', u'p4', u'p2'],
#                               fans = [0, 0 , 0, 0],
#                               roundWind = 'south',
#                               seatWind = 'east',
#                               parent = session)
#    hand.put()
    
    return http.HttpResponse(str(game.key()) + str(session.key()))
